package com.suneast.suneaststore.util.net.upload;

import android.util.Log;

import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.suneast.suneaststore.modules.common.Flag;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class QiNiuCloud extends CloudStorageVendor {
    private final static String TAG = QiNiuCloud.class.getSimpleName();

    private static QiNiuCloud instance = null;

    static QiNiuCloud get() {
        if (instance == null) {
            synchronized (QiNiuCloud.class) {
                if (instance == null) {
                    instance = new QiNiuCloud();
                }
            }
        }
        return instance;
    }

    private final UploadManager uploadManager;

    private QiNiuCloud() {
        uploadManager = new UploadManager();
    }

    private class Task {
        private final String key;
        private boolean cancel;

        private Task(String key) {
            this.key = key;
            this.cancel = false;
        }

        private boolean isCancelled() {
            return cancel;
        }
    }

    private final List<Task> upTasks = new ArrayList<>();

    @Override
    void store(File file, String token, String key) {
        final Task task = new Task(key);
        upTasks.add(task);
        UploadOptions options = new UploadOptions(null, null, false,
                (pKey, percent) -> EventBus.getDefault().post(new ProgressEvent(pKey, percent)), // Progress
                task::isCancelled/* Canceled */); // 暂时先这些参数测试
        uploadManager.put(file, key, token,
                (cKey, info, response) -> { // Complete
                    for (int i = 0, len = upTasks.size(); i < len;) {
                        if (cKey.equals(upTasks.get(i).key)) {
                            upTasks.remove(i);
                            len--;
                        } else {
                            i++;
                        }
                    }
                    if (!info.isCancelled()) {
                        EventBus.getDefault().post(new ResultEvent(info.isOK()
                                ? Flag.Result.SUCCEED : Flag.Result.FAILURE, cKey));
                    }
                },
                options);
    }

    @Override
    void get(String url) {

    }

    /**
     * 取消上传文件
     *
     * @param key 文件的标识
     */
    @Override
    void cancel(String key) {
        for (int i = 0, len = upTasks.size(); i < len; i++) {
            Task task = upTasks.get(i);
            if (key.equals(task.key)) {
                task.cancel = true;
            }
        }
    }
}
